const crypto = require("crypto");
const Employee = require("../models/employee");
const { returnFn } = require("../config/returnFn");

const checkRootLogin = (req, res, next) => {
    if (!req.session.employee) {
        return returnFn(res, 400, "未登录");
    }
    returnFn(res, 200, "已登录");
}

const employeeLogin = function(req, res) {
    let username = req.body.username;
    let pwd = req.body.password;
    let md5 = crypto.createHash("md5");
    let password = md5.update(pwd).digest("base64");

    Employee.getUserByName(username, function(err, result) {
        if (!result) return returnFn(res, 404, "用户名不存在");
        if (result.password != password) return returnFn(res, 401, "密码错误");

        req.session.employee = result;
        returnFn(res, 200);
    });
}

const employeeLogout = function(req, res) {
    req.session.employee = null;
    returnFn(res, 200);
}

module.exports = {
    checkRootLogin,
    employeeLogin,
    employeeLogout
}